use std::io::{ErrorKind, Read, Write};
use std::net::TcpStream;
use tracing::{error, info};

#[derive(Debug)]
pub struct GioClient {
    url: String,
    tcp_stream: TcpStream,
}

impl GioClient {
    pub fn new(url: String) -> Self {
        let tcp_stream = match TcpStream::connect(url.clone()) {
            Ok(stream) => stream,
            Err(e) => {
                error!("Failed to connect to server: {}", e);
                panic!("Error: {}", e.to_string());
            }
        };
        GioClient {
            url,
            tcp_stream
        }
    }

    pub fn s_set(&mut self, key: String, value: String) {

        if let Err(e) = self.tcp_stream.write_all(format!("SSET {} {}\n", key, value).as_bytes()) {
            error!("Failed to send command: {}", e);
        }
    }

    pub fn s_get(&mut self, key: String) -> Option<String> {
        info!("Response12345: 我想说点话", );
        if let Err(e) =  self.tcp_stream.write_all(format!("SGET {}\n", key).as_bytes()) {
            error!("Failed to write to stream: {}", e);
        }
        info!("Response12345: 我能到这吗", );
        let mut buf = [0; 2048];
        let mut response = String::new();

        match self.tcp_stream.read(&mut buf) {
            Ok(n) if n == 0 => {
                // 处理连接关闭的情况
                return None;
            }
            Ok(n) => {
                response.push_str(String::from_utf8_lossy(&buf[..n]).as_ref());
                info!("Response: {}", response);
            },
            Err(ref e) if e.kind() == ErrorKind::WouldBlock => {
                // 处理非阻塞情况，例如轮询或使用异步操作
                unimplemented!() // 需要实现具体的非阻塞处理逻辑
            }
            Err(e) => {
                error!("Failed to read from stream: {}", e);
                return None;
            }
        }

        info!("Response: {}", response);
        Some(response.trim().to_string())
    }

    pub fn s_remove(&mut self, key: String) {

        match self.tcp_stream.write_all(format!("SREMOVE {}\n", key).as_bytes()) {
            Ok(_) => {}
            Err(e) => {
                error!("Failed to write to stream: {}", e);
            }
        }
    }
}


#[cfg(test)]
mod tests {
    use tracing::Level;
    use tracing_subscriber::FmtSubscriber;
    use crate::http::{get_global_gio, init_global_gio};
    use crate::nosql::client::GioClient;



    #[test]
    fn test_client() {

        // 设置日志记录器
        let subscriber = FmtSubscriber::builder()
            .with_max_level(Level::DEBUG)
            .finish();
        tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");

        // let mut gio_client = GioClient::new("localhost:7423".to_string());

        init_global_gio();

        let mut gio_client = get_global_gio().lock().unwrap();

        gio_client.s_get("sgasfasdfawfesdg".to_string());
    }


}